package com.wehealth;

//import android.app.Fragment;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.security.acl.Group;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import u.aly.aa;

import com.umeng.analytics.MobclickAgent;
import com.wehealth.adapter.Adapter_NewsList;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.JsonReader;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;


public class News_List extends Fragment{
	
	
	private static final int NET_ERROR = -100;
	private static  String JSONResult;
	
	private List<String> listData;
	private List<String> listID;
	
	private ListView listView;
	private MainActivity activity;
			
	public  News_List()
	{
		
		Log.i("init:", "News_List"); 
	}
	
	
	private void  InitThisView() throws IOException
	{
		 String urlAPI = "http://www.552120.com/API/News_GetTitleList.aspx";
		 HttpPost httpRequest= new HttpPost(urlAPI);
		 
		 List <NameValuePair> params = new ArrayList <NameValuePair>();

		 try
		 {
			 httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8) );
			
			 HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);
			 
			 if(httpResponse.getStatusLine().getStatusCode() == 200)
			 {
				 JSONResult = EntityUtils.toString(httpResponse.getEntity());
			 }

			 
		 }
		 catch(Exception e)
		 {
			
			 Log.e("error:",  e.toString());
			 
		 }

	}
	
	

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

		return  inflater.inflate(R.layout.news_list, null);
	}
	
	
	
	public void onActivityCreated(Bundle savedInstanceState){
		
		super.onActivityCreated(savedInstanceState);
		
		Log.i("OnActivityCreated:", "test"); 
	
		
	
		//读取接口数据
		new Thread(){
			@Override
			public void run(){
			//你要执行的方法
				try {
					InitThisView();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			//执行完毕后给handler发送一个空消息
			handler.sendEmptyMessage(0);
			}
			}.start();

			 

		
		
		 activity = (MainActivity)getActivity();
		
		MobclickAgent.openActivityDurationTrack(false);
		//返回主页按钮-------------------------------------------------------//
		 Button bBack = (Button) activity.findViewById(R.id.bBack_NewsList);
			
		 bBack.setOnClickListener(new View.OnClickListener()
			{
				public void onClick(View v)
				{
				    activity.switchContentHome();
				}
			});
			
		//------------------------------------------------------------------//
		
		 
		 
	}
	
	
	
	//定义Handler对象
	private Handler handler =new Handler(){
		@Override
		//当有消息发送出来的时候就执行Handler的这个方法
		public void handleMessage(Message msg){
		super.handleMessage(msg);
		//处理UI
    		if(JSONResult!=null){
    		    BindList(JSONResult);
    		}else{
    		    activity.openDialogBt(NET_ERROR); 
    		}
		}
	};
	

	
	//将JSON数据绑定到LISTVIEW
	private void BindList(String strJSON)
	{
		try 
		{      
		    Log.i("json:", strJSON);
		    //String strJS = "{ \"result\": [ { \"ID\":\"250\", \"title\": \"亲子交流存在性别差异 女宝宝更喜欢听妈妈讲话\"} , { \"ID\":\"251\", \"title\": \"这里是新闻标题2\"} ] }";
		    
		    try
		    {
			    JSONObject jsonObject = new JSONObject(strJSON);   
			    JSONArray  aNews =  new JSONArray( jsonObject.getString("result") );		    
			    listData = new ArrayList<String>();
			    listID = new ArrayList<String>();
			    
			    for(int i=0; i<aNews.length(); i++)
			    {
			         listID.add(aNews.getJSONObject(i).getString("ID"));
			    		listData.add(aNews.getJSONObject(i).getString("title"));
			    }
			    
			    /*
			    listData = new ArrayList<String>();
			    listData.add("测试数据1");
			    listData.add("测试数据2");
			    listData.add("测试数据3");
			    listData.add("测试数据4");
			    */
		        
			    
			    MainActivity activity = (MainActivity)getActivity();
				
			    listView = (ListView) activity.findViewById(R.id.lvNews);
				 
			      Adapter_NewsList adapter = new Adapter_NewsList(activity, listData);
		        listView.setAdapter(adapter);
		        
		        //SIMMON_ADD begin
		        listView.setOnItemClickListener(new OnItemClickListener() {

					@Override
					public void onItemClick(AdapterView<?> parent, View view,
							int pos, long pos2) {
						// TODO Auto-generated method stub
						News_Message news_message = new News_Message();
						
						//这一处将来要进行修改
						news_message.setNewsId(listID.get(pos));
						//news_message.setNewsId("58");
						
						if (getActivity() instanceof MainActivity)
						{
							MainActivity activity = (MainActivity) getActivity();
							
							activity.switchContent(news_message);
						}
						
					}
				});
		        //SIMMON_ADD end
		        
		        
			    
			    //Log.i("the title: ", aNews.getJSONObject(1).getString("title"));  
		    }
		    catch(JSONException ex)
		    {
		    		Log.e("JSON Error: ", ex.toString()); 
		    }
		    
		 
		} 
		catch (Exception ex) 
		{  
		    
			Log.e("error: ",  ex.toString());
		}
	}
	
    @Override
    public void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        MobclickAgent.onPageEnd("News_list"); 
    }


    @Override
    public void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        MobclickAgent.onPageStart("News_list"); 
    }


//	@Override
//	public boolean onKey(View arg0, int arg1, KeyEvent event) {
//		// TODO Auto-generated method stub
//		Log.d("SIMMON","  onKey");
//        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK && 
//        		event.getAction() == KeyEvent.ACTION_DOWN) {
//			Home vHome = new Home();
//			if (getActivity() instanceof MainActivity)
//			{
//				MainActivity activity = (MainActivity) getActivity();
//				
//				activity.switchContent(vHome);
//			}
//		}
//		return true;
//	}

    
    
    
    
    
    

}



